package com.na.game.ui;

import java.util.Vector;

import android.graphics.Color;

import com.na.game.GameManager.Clazz;
import com.na.game.event.Updater;
import com.na.game.graphics.Graphics;
import com.na.game.graphics.Painter;
import com.na.game.util.GameConfig;

public class UIManager implements Updater, Painter, Clazz {

	// pending push or pop ui
	class Pending {
		byte type;
		UI ui;
		Pending(byte type, UI ui) {
			this.type = type;
			this.ui = ui;
		}
	}
	
	private Vector<UI> uis = new Vector<UI>();
	
	private static final byte PENDING_POP_UI = 0;
	private static final byte PENDING_PUSH_UI = 1;
	private Vector<Pending> pendings = new Vector<Pending>();
	private int pendingPopCount;
	
	@Override
	public void update() {
		int size = pendings.size();
		if (size > 0) {
			for (int i = 0; i < size; i++) {
				Pending pending = pendings.elementAt(i);
				if (pending.type == PENDING_POP_UI) {
					UI ui = uis.remove(uis.size() - 1);
					ui.destroy();
				} else {
					UI ui = pending.ui;
					ui.init();
					uis.addElement(ui);
				}
			}
			pendings.removeAllElements();
			pendingPopCount = 0;
		}
		
		int pos = getFirstUntransparentUIPos();
		size = uis.size();
		for (int i = pos; i < size; i++) {
			uis.elementAt(i).update();
		}
	}

	@Override
	public void paint(Graphics g) {
		g.setColor(Color.BLACK);
		g.setClip(0, 0, GameConfig.STANDARD_WIDTH, GameConfig.STANDARD_HEIGHT);
		g.fillRect(0, 0, GameConfig.STANDARD_WIDTH, GameConfig.STANDARD_HEIGHT);
		int pos = getFirstUntransparentUIPos();
		int size = uis.size();
		for (int i = pos; i < size; i++) {
			uis.elementAt(i).paint(g);
		}
	}
	
	private int getFirstUntransparentUIPos() {
		for (int i = uis.size() - 1; i >= 0; i--) {
			if (!uis.elementAt(i).isTransparent()) {
				return i;
			}
		}
		return 0;
	}
	
	public void pushUI(UI ui) {
		pendings.addElement(new Pending(PENDING_PUSH_UI, ui));
	}
	
	public void popUI() {
		Pending previous = pendings.isEmpty() ? null : pendings.elementAt(pendings.size() - 1);
		if (previous != null && previous.type == PENDING_PUSH_UI) {
			pendings.removeElementAt(pendings.size() - 1);
			return;
		}
		
		if (uis.size() > pendingPopCount) {
			pendings.addElement(new Pending(PENDING_POP_UI, null));
			pendingPopCount++;
		}
	}
	
	public UI getTopUI() {
		if (uis.isEmpty()) {
			return null;
		}
		return uis.elementAt(uis.size() - 1);
	}

	@Override
	public Class<?> getClazz() {
		return getClass();
	}
	
}
